package com.jinzhi.jzapi.training.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.configconsts.wxconsts.LinkConfiggure;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.common.vo.WxPayConfig;
import com.jinzhi.common.vo.WxPayVo;
import com.jinzhi.jzapi.training.pojo.*;
import com.jinzhi.jzweb.dao.ClassesExaminationSubmitAnswersDao;
import com.jinzhi.jzweb.dao.StudentPaperSubmitAnswersDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ChainBase;
import org.apache.commons.chain.impl.ContextBase;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/courses")
public class ApiCoursesController extends BaseController {
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private DiscussService discussService;
    @Autowired
    private DictService dictService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ChapterItemBankService chapterItemBankService;
    @Autowired
    private TrainingResourcesService trainingResourcesService;
    @Autowired
    private TrainingResultsService trainingResultsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CourseLearnsService courseLearnsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private CoustuQuestionsAnswersService coustuQuestionsAnswersService;
    @Autowired
    private UserService userService;
    @Autowired
    private WxPayConfig wxPayConfig;
    @Autowired
    private ChainBase wxPayCoursesOrderChain, wxPayNotifyCoursesOrderChain;
    @Autowired
    private StuClassService stuClassService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private CoursesClassService coursesClassService;
    @Autowired
    private PapersDeploymentService papersDeploymentService;
    @Autowired
    private StudentPaperSubmitService studentPaperSubmitService;
    @Autowired
    private MajorItemBankService majorItemBankService;
    @Autowired
    private StudentPaperSubmitAnswersService studentPaperSubmitAnswersService;
    @Autowired
    private ClassesExaminationPaperService classesExaminationPaperService;
    @Autowired
    private ClassesExaminationSubmitService classesExaminationSubmitService;
    @Autowired
    private ClassesExaminationSubmitAnswersService classesExaminationSubmitAnswersService;

    private static BigDecimal bigDecimal;

    static {
        bigDecimal = new BigDecimal(100);
    }

    /**
     * api小程序端-课程列表接口--公开方法，不需要登录
     *
     * @Description: 课程列表接口（需分页），参数：页码，显示数，课程名称（筛选条件），证书概况id（筛选条件）
     * @Param: [current, number, name, profileId]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selCourseList")
    @Log("api小程序端-课程列表接口")
    @ApiOperation(value = "api小程序端-课程列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCourseList(String current, String number, String name, String profileId) {
        Map map = new HashMap();
        map.put("name", name);
        if (StringUtils.isNotBlank(profileId)) {
            map.put("profileId", Long.parseLong(profileId));
        } else {
            map.put("profileId", null);
        }
        Page<CoursesListVo> page = coursesService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        return ApiResult.success(page);
    }


    /**
     * api小程序端-课程详情接口--公开方法，不需要登录
     *
     * @Description: 获取课程详细信息，参数：课程id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selCourseDetails")
    @Log("api小程序端-课程详情接口")
    @ApiOperation(value = "api小程序端-课程详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCourseDetails(String id) {
        if (StringUtils.isNotBlank(id)) {
            CoursesAndTeacherVo coursesAndTeacherVo = coursesService.selCourseDetail(Long.parseLong(id));
            return ApiResult.success(coursesAndTeacherVo);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }

//    /**
//     * api小程序端-课程章节列表信息接口--公开方法，不需要登录
//     *
//     * @Description: 课程对应的所有章节信息列表，参数：课程id
//     * @Param: [id]
//     * @return: com.jinzhi.common.utils.ApiResult<?>
//     * @Author: kl
//     * @Date: 2020-04-09
//     */
//    @GetMapping("/selChapterList")
//    @Log("api小程序端-课程章节列表信息接口")
//    @ApiOperation(value = "api小程序端-课程章节列表信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @Transactional
//    public ApiResult<?> selChapterList(String id) {
//        if (StringUtils.isNotBlank(id)) {
//            List<Map> mapList = new ArrayList<>();
//            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(id));
//            if (chapterDOS != null && chapterDOS.size() > 0) {
//                for (ChapterDO chapterDO : chapterDOS) {
//                    Map map1 = new HashMap();
//                    map1.put("id", chapterDO.getId());
//                    List<ChapterItemBankDO> chapterItemBankDOS = chapterItemBankService.findByKv("chapter_id", chapterDO.getId(), "type", 0);
//                    if (chapterItemBankDOS != null && chapterItemBankDOS.size() > 0) {
//                        map1.put("isChaItem", "true");
//                    } else {
//                        map1.put("isChaItem", "false");
//                    }
//                    if (chapterDO.getName() != null) {
//                        map1.put("name", chapterDO.getName());
//                    } else {
//                        map1.put("name", "");
//                    }
//                    map1.put("isFree", chapterDO.getIsFree());//是否免费
//
//                    List<TrainingResourcesDO> trainingResourcesDOS = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(), "type", 1);
////                    if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
////                        map1.put("videoDuration", trainingResourcesDOS.get(0).getVideoDuration());
////                    } else {
////                        map1.put("videoDuration", "");
////                    }
//                    map1.put("resources", trainingResourcesDOS);
//                    mapList.add(map1);
//                }
//            }
//            return ApiResult.success(mapList);
//        } else {
//            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
//        }
//    }

        @GetMapping("/selChapterList")
    @Log("api小程序端-课程章节列表信息接口")
    @ApiOperation(value = "api小程序端-课程章节列表信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selChapterList(String id) {
            List<Map> mapList = new ArrayList<>();
            if (StringUtils.isNotBlank(id)) {
                List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(id), "is_root", 1);
                if (chapterDOS != null && chapterDOS.size() > 0) {
                    for (ChapterDO chapterDO : chapterDOS) {
                        Map map1 = new HashMap();
                        map1.put("id", chapterDO.getId());
                        List<ChapterItemBankDO> chapterItemBankDOS = chapterItemBankService.findByKv("chapter_id", chapterDO.getId(), "type", 0);
                        if (chapterItemBankDOS != null && chapterItemBankDOS.size() > 0) {
                            map1.put("isChaItem", "true");
                        } else {
                            map1.put("isChaItem", "false");
                        }
                        if (chapterDO.getName() != null) {
                            map1.put("name", chapterDO.getName());
                        } else {
                            map1.put("name", "");
                        }
                        map1.put("isFree", chapterDO.getIsFree());//是否免费

                        map1.put("level", chapterDO.getLevel());//层级

                        List<TrainingResourcesDO> trainingResourcesDOS = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId());//,"type",1
                        if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
                            int i = 0;
                            for (TrainingResourcesDO r : trainingResourcesDOS) {
                                r.setRindex(i);
                                i++;
                            }
                        }
                        map1.put("resources", trainingResourcesDOS);
                        if (trainingResourcesDOS.size() > 0) {
                            map1.put("isHaveResources", 1);
                        } else {
                            map1.put("isHaveResources", 0);
                        }

                        List<Map> map1Children = new ArrayList<>();
                        List<ChapterDO> chapterDOS2 = chapterService.findByKv("courses_id", Long.parseLong(id), "parent_id", chapterDO.getId());
                        if (chapterDOS2 != null && chapterDOS2.size() > 0) {
                            for (ChapterDO chapterDO2 : chapterDOS2) {
                                Map map2 = new HashMap();
                                map2.put("id", chapterDO2.getId());
                                List<ChapterItemBankDO> chapterItemBankDOS2 = chapterItemBankService.findByKv("chapter_id", chapterDO2.getId(), "type", 0);
                                if (chapterItemBankDOS2 != null && chapterItemBankDOS2.size() > 0) {
                                    map2.put("isChaItem", "true");
                                } else {
                                    map2.put("isChaItem", "false");
                                }
                                if (chapterDO2.getName() != null) {
                                    map2.put("name", chapterDO2.getName());
                                } else {
                                    map2.put("name", "");
                                }
                                map2.put("isFree", chapterDO2.getIsFree());//是否免费

                                map2.put("level", chapterDO2.getLevel());//层级

                                List<TrainingResourcesDO> trainingResourcesDOS2 = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO2.getId());//,"type",1
                                if (trainingResourcesDOS2 != null && trainingResourcesDOS2.size() > 0) {
                                    int i = 0;
                                    for (TrainingResourcesDO r : trainingResourcesDOS2) {
                                        r.setRindex(i);
                                        i++;
                                    }
                                }
                                map2.put("resources", trainingResourcesDOS2);
                                if (trainingResourcesDOS2.size() > 0) {
                                    map2.put("isHaveResources", 1);
                                } else {
                                    map2.put("isHaveResources", 0);
                                }

                                List<Map> map2Children = new ArrayList<>();
                                List<ChapterDO> chapterDOS3 = chapterService.findByKv("courses_id", Long.parseLong(id), "parent_id", chapterDO2.getId());
                                if (chapterDOS3 != null && chapterDOS3.size() > 0) {
                                    for (ChapterDO chapterDO3 : chapterDOS3) {
                                        System.out.println("id:" + chapterDO3.getId() + " -- name:" + chapterDO.getName());
                                        Map map3 = new HashMap();
                                        map3.put("id", chapterDO3.getId());
                                        List<ChapterItemBankDO> chapterItemBankDOS3 = chapterItemBankService.findByKv("chapter_id", chapterDO3.getId(), "type", 0);
                                        if (chapterItemBankDOS3 != null && chapterItemBankDOS3.size() > 0) {
                                            map3.put("isChaItem", "true");
                                        } else {
                                            map3.put("isChaItem", "false");
                                        }
                                        if (chapterDO3.getName() != null) {
                                            map3.put("name", chapterDO3.getName());
                                        } else {
                                            map3.put("name", "");
                                        }
                                        map3.put("isFree", chapterDO3.getIsFree());//是否免费

                                        map3.put("level", chapterDO3.getLevel());//层级

                                        List<TrainingResourcesDO> trainingResourcesDOS3 = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO3.getId());//,"type",1
                                        if (trainingResourcesDOS3 != null && trainingResourcesDOS3.size() > 0) {
                                            int i = 0;
                                            for (TrainingResourcesDO r : trainingResourcesDOS3) {
                                                r.setRindex(i);
                                                i++;
                                            }
                                        }
                                        map3.put("resources", trainingResourcesDOS3);

                                        if (trainingResourcesDOS3.size() > 0) {
                                            map3.put("isHaveResources", 1);
                                        } else {
                                            map3.put("isHaveResources", 0);
                                        }
                                        map2Children.add(map3);
                                    }
                                    map2.put("isHaveChildren", 1);
                                    map2.put("children", map2Children);
                                } else {
                                    map2.put("isHaveChildren", 0);
                                    map2.put("children", "");
                                }
                                map1Children.add(map2);
                            }
                            map1.put("isHaveChildren", 1);
                            map1.put("children", map1Children);
                        } else {
                            map1.put("isHaveChildren", 0);
                            map1.put("children", "");
                        }
                        mapList.add(map1);
                    }
                }
            }
            return ApiResult.success(mapList);
    }

    /**
     * api小程序端-课程章节列表信息接口--公开方法，不需要登录
     *
     * @Description: 课程对应的所有章节信息列表，参数：课程id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selExtendList")
    @Log("api小程序端-课程扩展资料列表信息接口")
    @ApiOperation(value = "api小程序端-课程扩展资料列表信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selExtendList(String id) {
        if (StringUtils.isNotBlank(id)) {
            List<Map> mapList = new ArrayList<>();
            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(id));
            if (chapterDOS != null && chapterDOS.size() > 0) {
                for (ChapterDO chapterDO : chapterDOS) {
                    Map map1 = new HashMap();
                    map1.put("id", chapterDO.getId());
                    List<ChapterItemBankDO> chapterItemBankDOS = chapterItemBankService.findByKv("chapter_id", chapterDO.getId(), "type", 0);
                    if (chapterItemBankDOS != null && chapterItemBankDOS.size() > 0) {
                        map1.put("isChaItem", "true");
                    } else {
                        map1.put("isChaItem", "false");
                    }
                    if (chapterDO.getName() != null) {
                        map1.put("name", chapterDO.getName());
                    } else {
                        map1.put("name", "");
                    }
                    map1.put("isFree", chapterDO.getIsFree());//是否免费

                    List<TrainingResourcesDO> trainingResourcesDOS = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(), "type", 0);
                    trainingResourcesDOS.addAll(trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(), "type", 2));
                    trainingResourcesDOS.addAll(trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(), "type", 3));
//                    if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
//                        map1.put("videoDuration", trainingResourcesDOS.get(0).getVideoDuration());
//                    } else {
//                        map1.put("videoDuration", "");
//                    }
                    map1.put("resources", trainingResourcesDOS);
                    mapList.add(map1);
                }
            }
            return ApiResult.success(mapList);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }

    /**
     * api小程序端-章节详情接口
     *
     * @Description: 获取某章节的详细信息以及所有资源信息；参数：章节id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-10
     */
    @GetMapping("/selChapterDetails")
    @Log("api小程序端-章节详情接口")
    @ApiOperation(value = "api小程序端-章节详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selChapterDetails(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id, String chapterId) {
        System.out.println(id + "\n" + chapterId);
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isNotBlank(chapterId)) {
            ChapterDO chapterDO = chapterService.selectById(chapterId);
            if (chapterDO != null) {
                if (chapterDO.getIsFree().equals(1)) {
                    OrderDO courseOrderDO = orderService.findOneByKv("user_id", user.getId(), "object_id", chapterDO.getCoursesId());
                    if (courseOrderDO != null) {
                        if (courseOrderDO.getState() == 4) {
                            Map map = new HashMap();
                            map.put("code", 40024);
                            map.put("msg", "该课程已过期，请购买后重试！");
                            return ApiResult.success("请求成功", map);
                        } else if (courseOrderDO.getState() == 1) {
                            Map map = new HashMap();
                            map.put("code", 40025);
                            map.put("msg", "请支付后重试！");
                            return ApiResult.success("请求成功", map);
                        }
                    } else {
                        Map map = new HashMap();
                        map.put("code", ApiEnumError.NOPAYCOURSE.getCode());
                        map.put("msg", ApiEnumError.NOPAYCOURSE.getMsg());
                        return ApiResult.success("请求成功", map);
                    }
                }

                Map map = new HashMap();
                map.put("id", chapterDO.getId());
                map.put("name", chapterDO.getName());
                map.put("introduce", chapterDO.getIntroduce());
                map.put("minTime", chapterDO.getMinTime());
                map.put("isFree", chapterDO.getIsFree());

                Map mmp = new HashMap();
                mmp.put("id", id);
                TrainingResourcesDO TraResourcesDO = trainingResourcesService.findOneByKv("id", id);
                map.put("traRes", TraResourcesDO);

                return ApiResult.success(map);
            } else {
                return ApiResult.build(ApiEnumError.formatFail.getCode(), "信息错误，请稍后重试");
            }
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }

    /**
     * api小程序端-课程订单提交接口
     *
     * @Description: 用户提交课程购买订单；参数：验证token，课程id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-10
     */
    @PostMapping("/selCourseOrder")
    @Log("api小程序端-课程订单提交接口")
    @ApiOperation(value = "api小程序端-课程订单提交接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selCourseOrder(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        CoursesDO coursesDO = coursesService.selectById(Long.parseLong(id));
        if (coursesDO != null) {
            OrderDO orderDO1 = orderService.findOneByKv("object_id", coursesDO.getId(), "user_id", user.getId());
            if (orderDO1 == null) {
                OrderDO orderDO = new OrderDO();
                orderDO.setType(0);
                orderDO.setObjectId(Long.parseLong(id));//课程id
                orderDO.setUserId(user.getId());//会员id
                orderDO.setName(coursesDO.getName());//课程名
                orderDO.setOrderAmount(coursesDO.getSpecialPrice());//课程实付金额
                if (coursesDO.getSpecialPrice() == 0) {
                    orderDO.setState(0);//如价格为0，则直接设置为已支付
                    orderDO.setPayTime(new Date());//购买时间
                } else {
                    orderDO.setState(1);//默认未付款
                }
                Map map1 = new HashMap();
                map1.put("name", "课程有效期");
                map1.put("type", "effective_times");
                String times = dictService.selDicBy(map1);
                //获取课程有效期,如没有，直接默认一年
                if (times != null) {
                    //判断是否为数字,如不是，直接默认一年
                    if (IdCardUtil.isNumeric(times)) {
                        orderDO.setEffectiveTime(Double.parseDouble(times));
                    } else {
                        orderDO.setEffectiveTime(1.0);
                    }
                } else {
                    orderDO.setEffectiveTime(1.0);
                }

                boolean b = orderService.insert(orderDO);
                if (b) {
                    Map map = new HashMap();
                    map.put("orderId", orderDO.getId());//课程订单id
                    return ApiResult.success(map);
                } else {
                    return ApiResult.build(ApiEnumError.SUMBITERR.getCode(), ApiEnumError.SUMBITERR.getMsg());
                }
            } else {
                return ApiResult.build(ApiEnumError.ALREADYPAYCOURSE.getCode(), ApiEnumError.ALREADYPAYCOURSE.getMsg());
            }

        } else {
            return ApiResult.build(ApiEnumError.coursesErr.getCode(), ApiEnumError.coursesErr.getMsg());
        }
    }

    /**
     * api小程序端-学员购买课程微信支付接口
     *
     * @Description: 微信支付，参数：token令牌，wxpayVO虚拟实体（接收参数total_fee-支付金额，body-支付内容，trade_type-支付类型），课程订单id
     * @Param: [token, wxPayVo, courseOrderId]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-13
     */
    @PostMapping("/wxPay")
    @Log("api小程序端-学员购买课程微信支付接口")
    @ApiOperation(value = "api小程序端-学员购买课程微信支付接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @Transactional
    public ApiResult<?> wxPay(@RequestHeader(value = TOKEN_TAG, required = false) String token, @Validated WxPayVo wxPayVo, String courseOrderId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        ApiResult apiResult = new ApiResult();
        try {
            //判断课程订单id是否为空
            if (null == courseOrderId || courseOrderId == "undefined") {
                return ApiResult.build(ApiEnumError.lackParameter.getCode(), "缺少参数:courseOrderId");
            }

            OrderDO orderDO = orderService.selectById(Long.parseLong(courseOrderId));

            if (StringUtils.isBlank(user.getTraOpenId())) {
                return ApiResult.build(ApiEnumError.NOOPENID.getCode(), ApiEnumError.NOOPENID.getMsg());
            }

            String openId = user.getTraOpenId();
            //通过uuid生成商户id
            String out_trade_no = UUID.randomUUID().toString().replace("-", "");
            //生成32为随机数
            String randomStringBy = StringUtil.getRandomStringByLength(32);

            wxPayVo.setAppid(wxPayConfig.getTraAppid());//appid（微信公众号）
            wxPayVo.setMch_id(wxPayConfig.getMerNo());//商户id
            wxPayVo.setNotify_url(wxPayConfig.getCoursesOrderNotify());//回调地址
            wxPayVo.setSpbill_create_ip(wxPayConfig.getIp());//ip地址
            wxPayVo.setOut_trade_no(out_trade_no);
            wxPayVo.setNonce_str(randomStringBy);
            wxPayVo.setTotal_fee(new BigDecimal(orderDO.getOrderAmount().toString()).multiply(bigDecimal).setScale(0).toString());//支付金额
            wxPayVo.setOpenId(openId);
            wxPayVo.setLabel(WxPayLabelEnum.order.getTag());
            wxPayVo.setType(AppEnum.training.getTag());

            log.info("商户订单号:" + out_trade_no);

            //保存用户id至缓存，为后面回调提供
            EhCacheUtil.put(out_trade_no + ":courseOrderId", Long.parseLong(courseOrderId));

            //创建上下文
            Context context = new ContextBase();

            //微信支付对象
            context.put(LinkConfiggure.WX_PAY_VO, wxPayVo);
            //固定返回对象
            context.put(LinkConfiggure.API_RESULT, apiResult);
            //订单id(考生报名id）
            context.put("courseOrderId", Long.parseLong(courseOrderId));
            //用户id
            context.put("user_id", user.getId());
            //商户订单号
            context.put("out_trade_no", out_trade_no);

            //开始链路
            wxPayCoursesOrderChain.execute(context);
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new RuntimeException(e);
        }
        Map map = new HashMap();
        map.put("type", "wx");
        map.put("wx", apiResult);
        return ApiResult.success(map);
    }


    /**
     * 微信支付回调接口
     *
     * @Description: 微信支付回调，供微信调用
     * @Param: [request]
     * @return: java.lang.String
     * @Author: kl
     * @Date: 2020-04-13
     */
//    @ExceptionHandler(Exception.class)
    @PostMapping("/wxNotify")
    public String wxNotify(HttpServletRequest request) {
        StringUtil stringUtil = new StringUtil();
        return stringUtil.getWxNotify(request, wxPayNotifyCoursesOrderChain, wxPayConfig);
    }


    /**
     * api小程序端-个人中心—我的课程列表接口
     *
     * @Description: 查询当前用户的课程列表信息；参数：页码，显示数，状态（筛选条件）
     * @Param: [token, current, number, state]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @GetMapping("/selMyCourseList")
    @Log("api小程序端-个人中心—我的课程列表接口")
    @ApiOperation("api小程序端-个人中心—我的课程列表接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyCourseList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number, String state) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        Page<MyCourseListVo> page = orderService.selByStateUserId(Integer.parseInt(current), Integer.parseInt(number), map);
        if (page != null && page.getTotal() > 0) {
            List list = new ArrayList();
            for (int i = 0; i < page.getRecords().size(); i++) {
                MyCourseListVo obj = (MyCourseListVo) page.getRecords().get(i);
                if (obj.getTeacherName() != null) {
                    ExpertsDO expertsDO = expertsService.findOneByKv("user_id", obj.getTeacherName(), "type", 4);
                    if (expertsDO != null) {
                        obj.setTeacherName(expertsDO.getName());
                    } else {
                        obj.setTeacherName("敬请期待");
                    }
                }

                long allSize = 0;//总章节数
                List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", obj.getId());
                if (chapterDOS != null && chapterDOS.size() > 0) {
                    allSize = chapterDOS.size();
                }

                //是否进行过测试(0没有，1已测试）
                Map map1 = new HashMap();
                map1.put("coursesId", obj.getId());
                map1.put("userId", user.getId());
                boolean trac = trainingResultsService.selResultsStateList(map1);
                if (trac) {
                    obj.setIsTestScores(1);
                } else {
                    obj.setIsTestScores(0);
                }

                CourseLearnsDO courseLearnsDO = courseLearnsService.findOneByKv("courses_id", obj.getId(), "user_id", user.getId());
                if (courseLearnsDO != null) {
                    long reSize = courseLearnsDO.getCompletionNumber();//完成章节数
                    if (courseLearnsDO.getState() == 0) {
                        obj.setProcess("100%");
                    } else {
                        CoursesDO coursesDO = coursesService.selectById(obj.getId());
                        if (coursesDO.getAdoptFactor().equals("所有章节通过")) {
                            if (allSize != 0) {
                                if (reSize * 100 / allSize >= 100) {
                                    obj.setProcess("100%");
                                } else {
                                    obj.setProcess((reSize * 100 / allSize) + "%");
                                }
                            } else {
                                obj.setProcess("0%");
                            }
                        } else if (coursesDO.getAdoptFactor().equals("所有章节通过以及测试达到合格")) {
                            if (allSize != 0) {
                                if (reSize != 0) {
                                    if ((reSize / allSize) * 100 >= 100) {
                                        obj.setProcess("90%");
                                    } else {
                                        obj.setProcess(((reSize * 100 / allSize) * 0.9) + "%");
                                    }
                                } else {
                                    obj.setProcess("0%");
                                }
                            } else {
                                obj.setProcess("0%");
                            }
                        } else {
                            //课程通过条件为：测试通过；那么这里的情况是课程没有通过，那么无论是有没有测试，都是返回百分之0
                            obj.setProcess("0%");
                        }
                    }
                } else {
                    obj.setProcess("0%");
                }


                list.add(obj);
            }
            page.setRecords(list);
        }

        return ApiResult.success(page);
    }


    /**
     * api小程序端-个人中心—我的班级列表接口
     *
     * @Description: 查询当前用户的班级列表信息；参数：页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @GetMapping("/selMyClasssList")
    @Log("api小程序端-个人中心—我的班级列表接口")
    @ApiOperation("api小程序端-个人中心—我的班级列表接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyClasssList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Wrapper<StuClassDO> wrapper = new EntityWrapper<StuClassDO>().orderBy("id", false);
        wrapper.eq("user_id", user.getId());

        Page<Map<String, Object>> page = stuClassService.selectMapsPage(new Page(Integer.parseInt(current), Integer.parseInt(number)), wrapper);
        if (page != null && page.getTotal() > 0) {
            List list = new ArrayList();
            for (int i = 0; i < page.getRecords().size(); i++) {
                System.out.println("page.getRecords().get(0):" + page.getRecords().get(i).toString());
                StuClassDO stuClassDO = this.stuClassService.selectById(Long.valueOf(page.getRecords().get(i).get("id").toString()));
                Wrapper<StudentClassesDO> swrapper = new EntityWrapper<StudentClassesDO>().orderBy("id", false);
                swrapper.eq("id", stuClassDO.getClassId());
                List<StudentClassesDO> StudentClasses = classesService.selectList(swrapper);
                if (StudentClasses.size() > 0) {
                    stuClassDO.setStudentClassName(StudentClasses.get(0).getName());
                    stuClassDO.setThumbnail(StudentClasses.get(0).getThumbnail());
                    stuClassDO.setDescribe(StudentClasses.get(0).getDescribe());

                    //是否有班级作业
                    Wrapper<PapersDeploymentDO> paperSwrapper = new EntityWrapper<PapersDeploymentDO>().orderBy("id", false);
                    paperSwrapper.eq("class_id", stuClassDO.getClassId());
                    List<PapersDeploymentDO> deploymentDOS = papersDeploymentService.selectList(paperSwrapper);
                    if (deploymentDOS.size() > 0) {
                        stuClassDO.setIsHaveTasks(1);
                        for (PapersDeploymentDO ps: deploymentDOS) {
                            //是否有新的班级作业
                            Wrapper<StudentPaperSubmitDO> paperSubmitSwrapper = new EntityWrapper<StudentPaperSubmitDO>().orderBy("id", false);
                            paperSubmitSwrapper.eq("papers_deployment_id", ps.getId());
                            paperSubmitSwrapper.eq("stu_id", user.getId());
                            List<StudentPaperSubmitDO> paperSubmitS = studentPaperSubmitService.selectList(paperSubmitSwrapper);
                            if (paperSubmitS.size() > 0) {
                                stuClassDO.setIsHaveNewTasks(0);
                            }else {
                                //是否已截止
                                Date sd1 = ps.getEndTime();
                                Date sd2 = new Date();

                                if(sd2.before(sd1)) {//没有截止
                                    stuClassDO.setIsHaveNewTasks(1);
                                }
                            }
                        }
                    }else {
                        stuClassDO.setIsHaveTasks(1);
                    }

                    //是否有班级考试
                    Wrapper<ClassesExaminationPaperDO> CEPWrapper = new EntityWrapper<ClassesExaminationPaperDO>().orderBy("id", false);
                    CEPWrapper.eq("class_id", stuClassDO.getClassId());
                    CEPWrapper.eq("status", 1);
                    List<ClassesExaminationPaperDO> CEPDOS = classesExaminationPaperService.selectList(CEPWrapper);
                    if (CEPDOS.size() > 0) {
                        stuClassDO.setIsHaveExamnation(1);
                        for (ClassesExaminationPaperDO CEP: CEPDOS) {
                            //是否有新的班级考试
                            Wrapper<ClassesExaminationSubmitDO> CESwrapper = new EntityWrapper<ClassesExaminationSubmitDO>().orderBy("id", false);
                            CESwrapper.eq("classes_examination_paper_id", CEP.getId());
                            CESwrapper.eq("stu_id", user.getId());
                            CESwrapper.eq("stu_id", user.getId());
                            List<ClassesExaminationSubmitDO> CESubmitS = classesExaminationSubmitService.selectList(CESwrapper);
                            if (CESubmitS.size() > 0) {
                                stuClassDO.setIsHaveNewExamnation(0);
                            }else {
                                //是否已截止
                                Date sd1 = CEP.getEndTime();
                                Date sd2 = new Date();

                                if(sd2.before(sd1)) {//没有截止
                                    stuClassDO.setIsHaveNewExamnation(1);
                                }
                            }
                        }
                    }else {
                        stuClassDO.setIsHaveExamnation(1);
                    }
                } else {
                    stuClassDO.setStudentClassName("");
                    stuClassDO.setThumbnail("");
                    stuClassDO.setDescribe("");
                    stuClassDO.setIsHaveTasks(0);
                    stuClassDO.setIsHaveNewTasks(0);
                    stuClassDO.setIsHaveExamnation(0);
                    stuClassDO.setIsHaveNewExamnation(0);
                }
                list.add(stuClassDO);
            }
            page.setRecords(list);
        }

        return ApiResult.success(page);
    }

    /**
     * api小程序端-个人中心—加入班级接口
     *
     * @Description: 当前用户加入班级；参数：班级号
     * @Param: [token, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/intoStudentClass")
    @Log("api小程序端-个人中心—加入班级接口")
    @ApiOperation(value = "api小程序端-个人中心—我的班级列表接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> intoStudentClass(@RequestHeader(value = TOKEN_TAG, required = false) String token, String number) {
        System.out.println("number:" + number);
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Wrapper<StudentClassesDO> s = new EntityWrapper<StudentClassesDO>().orderBy("id", false);
        List<StudentClassesDO> StuClasses = classesService.selectList(s);
        if (StuClasses.size() > 0) {//一个学生只能加入一个班级
            return ApiResult.fail("只能加入一个班级！");
        }

        Wrapper<StudentClassesDO> swrapper = new EntityWrapper<StudentClassesDO>().orderBy("id", false);
        if (number != null) {
            swrapper.eq("id", Long.valueOf(number));
            List<StudentClassesDO> StudentClasses = classesService.selectList(swrapper);
            if (StudentClasses.size() > 0) {
                Wrapper<StuClassDO> swrapper2 = new EntityWrapper<StuClassDO>().orderBy("id", false);
                swrapper2.eq("user_id", user.getId());
                swrapper2.in("status", "0,1");//审核失败可重新申请
                List<StuClassDO> Stus = stuClassService.selectList(swrapper2);
                if (Stus.size() > 0) {
                    return ApiResult.fail("你已申请加入过该班级，无需再加入！");
                } else {
                    StuClassDO newStuClass = new StuClassDO();
                    newStuClass.setUserId(user.getId());
                    newStuClass.setClassId(StudentClasses.get(0).getId());
                    newStuClass.setStatus(0);
                    newStuClass.setAddTime(new Date());
                    this.stuClassService.insert(newStuClass);
                }
            } else {
                return ApiResult.fail("班级不存在！");
            }
            return ApiResult.success(1);
        } else {
            return ApiResult.fail("班级不存在！");
        }
    }


    /**
     * api小程序端-课程订单详情接口
     *
     * @Description: 根据课程订单id查询订单信息并返回；参数：token令牌、课程订单id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @GetMapping("/selMyCourseOrderDetials")
    @Log("api小程序端-课程订单详情接口")
    @ApiOperation("api小程序端-课程订单详情接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyCourseOrderDetials(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        OrderDO orderDO = orderService.selectById(Long.parseLong(id));
        if (orderDO != null) {
            return ApiResult.success(orderDO);
        } else {
            return ApiResult.build(ApiEnumError.NoInfrom.getCode(), ApiEnumError.NoInfrom.getMsg());
        }
    }

    @GetMapping("/selIsMyCourse")
    @Log("培训门户端—返回是否购买课程接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "培训门户端—返回是否购买课程接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selIsMyCourse(@RequestHeader(value = TOKEN_TAG, required = false) String token, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        //是否购买此课程(0是，1否)
        OrderDO order = orderService.findOneByKv("object_id", Long.parseLong(courseId), "user_id", user.getId());
        if (order != null) {
            map.put("isMyCourse", 0);
        } else {
            map.put("isMyCourse", 1);
        }
        return ApiResult.success(map);
    }


    @GetMapping("/selCoustuQueAns")
    @Log("api小程序端—课程问答列表分页查询接口")
    @Transactional
    @ApiOperation(value = "api小程序端—课程问答列表分页查询接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selCoustuQueAns(String current, String number, String courseId) {
        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }
        Map map = new HashMap();
        map.put("courseId", courseId);
        Page<CoustuQuestionsAnswersDO> page = coustuQuestionsAnswersService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            CoustuQuestionsAnswersDO obj = (CoustuQuestionsAnswersDO) page.getRecords().get(i);
            if (obj.getState() != null) {
                CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid", obj.getId());
                if (coustuQuestionsAnswersDO != null) {
                    UserDO userDo = userService.selectById(coustuQuestionsAnswersDO.getUserId());
                    if (userDo != null) {
                        obj.setTeaUserName(userDo.getName());
                    }
                    obj.setAnswers(coustuQuestionsAnswersDO.getContents());
                } else {
                    obj.setAnswers("暂无");
                }
            }
            if (obj.getUserId() != null) {
                UserDO userDO = userService.selectById(obj.getUserId());
                if (userDO != null) {
                    obj.setUserName(userDO.getUsername());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }


    @GetMapping("/selQuestions")
    @Log("api小程序端—学生查询自己的课程提问接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—学生查询自己的课程提问接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selQuestions(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }

        Map map = new HashMap();
        map.put("courseId", courseId);
        map.put("userId", user.getId());
        Page<CoustuQuestionsAnswersDO> page = coustuQuestionsAnswersService.selectMyListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        return ApiResult.success(page);
    }


    @GetMapping("/selQuestionsDetails")
    @Log("api小程序端—学生查询自己的课程提问详情接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—学生查询自己的课程提问详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selQuestionsDetails(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }

        Map map = new HashMap();
        CoustuQuestionsAnswersDO coustuQuestionsAnswersDOs = coustuQuestionsAnswersService.selectById(Long.parseLong(id));
        map.put("pid", coustuQuestionsAnswersDOs.getId());//问题id
        map.put("questions", coustuQuestionsAnswersDOs.getContents());//问题内容
        map.put("state", coustuQuestionsAnswersDOs.getState());//问题状态
        if (coustuQuestionsAnswersDOs.getState().equals(1)) {
            CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid", coustuQuestionsAnswersDOs.getId());
            if (coustuQuestionsAnswersDO != null) {
                map.put("id", coustuQuestionsAnswersDO.getId());//回答id
                map.put("answers", coustuQuestionsAnswersDO.getContents());//回答内容
                UserDO userDo = userService.selectById(coustuQuestionsAnswersDO.getUserId());
                if (userDo != null) {
                    map.put("teaUserName", userDo.getName());//老师名称
                } else {
                    map.put("teaUserName", "");//老师名称
                }
            } else {
                map.put("id", "");//回答id
                map.put("answers", "");//回答内容
            }
        }

        return ApiResult.success(map);
    }


    @PostMapping("/addQuestions")
    @Log("api小程序端—考生针对课程发起提问接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—考生针对课程发起提问接口", httpMethod = "Post", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addQuestions(@RequestHeader(value = TOKEN_TAG, required = false) String token, String courseId, String questions) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(questions)) {
            return ApiResult.lack("");//缺少参数
        }

        CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = new CoustuQuestionsAnswersDO();
        coustuQuestionsAnswersDO.setState(0);//默认未回答
        coustuQuestionsAnswersDO.setCoursesId(Long.parseLong(courseId));//课程id
        coustuQuestionsAnswersDO.setUserId(user.getId());//学生id
        coustuQuestionsAnswersDO.setContents(questions);//问题
        coustuQuestionsAnswersDO.setPid(0L);//默认为0，最高级

        boolean cc = coustuQuestionsAnswersService.insert(coustuQuestionsAnswersDO);
        return cc ? ApiResult.success() : ApiResult.fail("提问错误，请稍后重试！");
    }

    @GetMapping("/delQuestions")
    @Log("api小程序端—考生删除课程问题接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—考生删除课程问题接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addQuestions(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }

        CoustuQuestionsAnswersDO coustuQuestionsAnswers = coustuQuestionsAnswersService.selectById(Long.parseLong(id));
        if (coustuQuestionsAnswers.getUserId().equals(user.getId())) {
            if (coustuQuestionsAnswers.getState().equals(1)) {
                CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid", Long.parseLong(id));
                if (coustuQuestionsAnswersDO != null) {
                    coustuQuestionsAnswersService.deleteById(coustuQuestionsAnswersDO.getId());
                }
            }
            boolean dd = coustuQuestionsAnswersService.deleteById(Long.parseLong(id));
            return dd ? ApiResult.success() : ApiResult.fail("删除错误，请稍后重试！");
        } else {
            log.info("学生尝试删除别人的问题，请注意！");
            return ApiResult.fail("数据错误，请重试！");
        }
    }

    /**
     * 新增评论
     */
    @PostMapping("/addComment")
    @Log("新增评论接口")
    @ApiOperation(value = "新增评论接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addComment(@RequestHeader(value = TOKEN_TAG, required = false) String token,
                                   String message, String isAnonymous, String pid, String rootId, String coursesId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (coursesId == null || coursesId.equals("")) {
            return ApiResult.fail("当前课程不存在！");
        } else {
            CoursesDO coursesDO = this.coursesService.selectById(Long.valueOf(coursesId));
            if (coursesDO == null) {
                return ApiResult.fail("当前课程不存在！");
            }
        }
        if (message != null) {
            Wrapper<DiscussDO> wrapper = new EntityWrapper<DiscussDO>().orderBy("add_time", false);
            wrapper.eq("user_id", user.getId());

            //当天评论数
            int comment_day_num = 100;

            //评论单位时间(分钟)
            int comment_unit_time = 0;
            DictDO dictDO = dictService.findOneByKv("type", "comment_unit_time");
            if (dictDO != null && dictDO.getValue() != null && !dictDO.getValue().equals("")) {
                comment_unit_time = Integer.valueOf(dictDO.getValue());
            }

            //评论数量
            int comment_unit_num = 0;
            DictDO dictDO2 = dictService.findOneByKv("type", "comment_unit_num");
            if (dictDO2 != null && dictDO2.getValue() != null && !dictDO2.getValue().equals("")) {
                comment_unit_num = Integer.valueOf(dictDO2.getValue());
            }

            Date newDate = new Date();
            if (comment_unit_time != 0 && comment_unit_num != 0) {
                Calendar date = this.getTimeForSub(
                        0,
                        0,
                        Integer.valueOf(comment_unit_time),
                        0,
                        newDate
                );
                wrapper.between("add_time", date.getTime(), newDate);
                System.out.println("comment_unit_time:" + comment_unit_time);
                System.out.println("comment_unit_num:" + comment_unit_num);
                System.out.println("date:" + date.getTime());
                System.out.println("newDate:" + newDate);
                List<DiscussDO> discussDOS = discussService.selectList(wrapper);
                if (discussDOS.size() >= comment_unit_num) {
                    return ApiResult.fail("评论过于频繁，请稍候再试！");
                }
            }

            if (comment_day_num != 0) {
                wrapper.between("add_time", getStartTime(), getEndTime());
                List<DiscussDO> discussDOS = discussService.selectList(wrapper);
                if (discussDOS.size() >= comment_day_num) {
                    return ApiResult.fail("今日评论过于频繁，请稍候再试！");
                }
            }

            //关键字过虑
            String newMessage = message;
            String comment_keyword = "";
            DictDO dictDO3 = dictService.findOneByKv("type", "comment_keyword");
            if (dictDO3 != null && dictDO3.getValue() != null && !dictDO3.getValue().equals("")) {
                comment_keyword = dictDO3.getValue();
                if (comment_keyword != null && !comment_keyword.equals("")) {
                    String[] keywordList = comment_keyword.split(";");
                    if (keywordList.length > 0) {
                        for (int a = 0; a < keywordList.length; a++) {
                            if (newMessage != null && newMessage.contains(keywordList[a])) {
                                newMessage = newMessage.replace(keywordList[a], "***");
                                System.out.println("newMessage:" + a + " " + newMessage);
                            }
                        }
                    }
                }
            }
            System.out.println("newMessage:" + newMessage);

            DiscussDO discussDO = new DiscussDO();
            discussDO.setContent(newMessage);
            if (isAnonymous != null) {
                discussDO.setIsAnonymous(Integer.valueOf(isAnonymous));
            } else {
                discussDO.setIsAnonymous(0);
            }
            if (!pid.equals("-1") && !pid.equals("")) {
                DiscussDO parent = this.discussService.selectById(Long.valueOf(pid));
                discussDO.setFromUserId(parent.getUserId());
                discussDO.setPid(Long.valueOf(pid));
            } else {
                if (!rootId.equals("-1") && !rootId.equals("")) {
                    DiscussDO parent = this.discussService.selectById(Long.valueOf(rootId));
                    discussDO.setFromUserId(parent.getUserId());
                }
            }
            if (!rootId.equals("-1") && !rootId.equals("")) {
                discussDO.setRootId(Long.valueOf(rootId));
            }

            discussDO.setIsDelete(0);
            discussDO.setAddTime(newDate);
            discussDO.setUserId(user.getId());
            discussDO.setCoursesId(Long.valueOf(coursesId));

            if (this.discussService.insert(discussDO)) {
                return ApiResult.success(1);
            } else {
                return ApiResult.fail("添加评论失败，数据库错误！");
            }
        } else {
            return ApiResult.fail("请输入评论内容！");
        }
    }


    /**
     * 删除评论
     */
    @PostMapping("/deleteComment")
    @Log("删除评论接口")
    @ApiOperation(value = "删除评论接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> deleteComment(@RequestHeader(value = TOKEN_TAG, required = false) String token,
                                      String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (id == null || id.equals("")) {
            return ApiResult.fail("评论不存在！");
        } else {
            Wrapper<DiscussDO> wrapper = new EntityWrapper<DiscussDO>().orderBy("add_time", false);
            wrapper.eq("root_id", Long.valueOf(id));
            List<DiscussDO> discussDOS = discussService.selectList(wrapper);
            if (discussDOS != null && discussDOS.size() > 0) {
                return ApiResult.fail("删除评论失败，该评论下有子级！！");
            } else {
                DiscussDO discussDO = this.discussService.selectById(Long.valueOf(id));
                if (discussDO != null) {
                    discussDO.setIsDelete(1);
                    if (this.discussService.updateById(discussDO)) {
                        return ApiResult.fail("删除评论成功！");
                    } else {
                        return ApiResult.fail("删除评论失败，数据库错误！！");
                    }
                } else {
                    return ApiResult.fail("评论不存在！");
                }
            }
        }
    }


    /**
     * api小程序端-评论列表信息接口--公开方法，不需要登录
     *
     * @Description: 课程对应的根评论列表，参数：课程id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selCommentList")
    @Log("api小程序端-课程对应的根评论列表接口")
    @ApiOperation(value = "api小程序端-课程对应的根评论列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCommentList(String id, String rootId) {
        if (StringUtils.isNotBlank(id)) {
            List<Map> mapList = new ArrayList<>();
            Wrapper<DiscussDO> wrapper = new EntityWrapper<DiscussDO>().orderBy("add_time", false);
            wrapper.eq("courses_id", Long.parseLong(id));
            boolean isSelSub = false;
            if (rootId != null && !rootId.equals("")) {
                wrapper.eq("root_id", Long.valueOf(rootId));
                isSelSub = true;
            } else {
                wrapper.isNull("root_id");
            }

            List<DiscussDO> discussDOS = discussService.selectList(wrapper);
            if (discussDOS != null && discussDOS.size() > 0) {
                for (DiscussDO discussDO : discussDOS) {
                    Map map1 = new HashMap();
                    map1.put("id", discussDO.getId());

                    UserDO userDO = this.userService.selectById(discussDO.getUserId());
                    if (userDO != null) {
                        if (userDO.getHeadPortrait() != null) {
                            map1.put("headPortrait", userDO.getHeadPortrait());
                        } else {
                            map1.put("headPortrait", "");
                        }
                        if (userDO.getUsername() != null) {
                            map1.put("userName", userDO.getUsername());
                        } else {
                            if (userDO.getName() != null) {
                                map1.put("userName", userDO.getName());
                            } else {
                                map1.put("userName", "");
                            }
                        }
                    } else {
                        map1.put("userName", "");
                        map1.put("headPortrait", "");
                    }

                    if (discussDO.getIsAnonymous() != null) {
                        map1.put("isAnonymous", discussDO.getIsAnonymous());
                    } else {
                        map1.put("isAnonymous", 0);
                    }

                    UserDO fromUserDO = this.userService.selectById(discussDO.getFromUserId());
                    if (fromUserDO != null) {
                        if (fromUserDO.getUsername() != null) {
                            map1.put("fromUserName", fromUserDO.getUsername());
                        } else {
                            if (fromUserDO.getName() != null) {
                                map1.put("fromUserName", fromUserDO.getName());
                            } else {
                                map1.put("fromUserName", "");
                            }
                        }
                    } else {
                        map1.put("fromUserName", "");
                    }

                    if (discussDO.getPid() != null) {
                        DiscussDO parent = this.discussService.selectById(discussDO.getPid());
                        if (parent.getIsAnonymous() == 1) {
                            map1.put("fromUserName", "匿名用户");
                        }
                    }

                    if (discussDO.getContent() != null) {
                        map1.put("content", discussDO.getContent());
                    } else {
                        map1.put("content", "");
                    }


                    if (discussDO.getIsDelete() != null) {
                        map1.put("isDelete", discussDO.getIsDelete());
                    } else {
                        map1.put("isDelete", 0);
                    }

                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map1.put("addTime", sf.format(discussDO.getAddTime()));


                    CoursesDO coursesDO = this.coursesService.selectById(Long.parseLong(id));
                    if (discussDO.getUserId().equals(coursesDO.getUserId())) {
                        map1.put("isTeacher", 1);
                    } else {
                        map1.put("isTeacher", 0);
                    }


                    //List list = new ArrayList();
                    if ((int) map1.get("isTeacher") == 0) {
                        map1.put("isStudent", 1);
                    } else {
                        map1.put("isStudent", 0);
                        OrganizationNewsDO org = this.organizationNewsService.selectById(coursesDO.getOrgId());
                        if (org != null) {
                            if (org.getName() != null) {
                                map1.put("orgName", org.getName());
                            } else {
                                map1.put("orgName", "");
                            }
                        } else {
                            map1.put("orgName", "");
                        }
                    }
                    if ((int) map1.get("isTeacher") == 0 && (int) map1.get("isAnonymous") == 0) {//不是老师且没有匿名，查询学生班级
                        List<StuClassDO> stuClassDOS = stuClassService.findByKv("user_id", discussDO.getUserId(), "status", 1);
                        if (stuClassDOS.size() > 0) {
                           /* for (StuClassDO c:stuClassDOS) {
                                StudentClassesDO classesDO = classesService.selectById(c.getClassId());
                                if(classesDO!=null){
                                    list.add(classesDO.getName());
                                }
                            }*/
                            StudentClassesDO classesDO = classesService.selectById(stuClassDOS.get(0).getClassId());
                            if (classesDO != null) {
                                map1.put("classesName", classesDO.getName());
                                OrganizationNewsDO org = this.organizationNewsService.selectById(classesDO.getOrgId());
                                if (org != null) {
                                    if (org.getName() != null) {
                                        map1.put("orgName", org.getName());
                                    } else {
                                        map1.put("orgName", "");
                                    }
                                } else {
                                    map1.put("orgName", "");
                                }
                            } else {
                                map1.put("classesName", "");
                                map1.put("orgName", "");
                            }

                        } else {
                            map1.put("classesName", "");
                            map1.put("orgName", "");
                        }
                    } else {
                        map1.put("classesName", "");
                    }
                    if (map1.get("classesName").toString().equals("")) {
                        map1.put("isStudent", 0);
                    }
                    // map1.put("classesNameSize", list.size());

                    if ((int) map1.get("isTeacher") == 0 && (int) map1.get("isTeacher") == 0) {
                        OrganizationNewsDO org = this.organizationNewsService.selectById(userDO.getOrgId());
                        if (org != null) {
                            if (org.getName() != null) {
                                map1.put("orgName", org.getName());
                            } else {
                                map1.put("orgName", "");
                            }
                        } else {
                            map1.put("orgName", "");
                        }
                    }

                    //时间
                    String timeStr = "";
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    java.util.Date now;
                    try {
                        String d = df.format(discussDO.getAddTime());
                        String d2 = df.format(new Date());
                        now = df.parse(d2);
                        java.util.Date date = df.parse(d);
                        long l = now.getTime() - date.getTime();
                        long day = l / (24 * 60 * 60 * 1000);
                        long hour = (l / (60 * 60 * 1000) - day * 24);
                        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
                        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

                        StringBuffer sb = new StringBuffer();
                        //sb.append("发表于：");
                        if (day > 0) {
                            sb.append(day + "天");
                        } else {
                            if (hour > 0) {
                                sb.append(hour + "小时");
                            } else {
                                if (min > 0) {
                                    sb.append(min + "分钟");
                                } else {
                                    sb.append(s + "秒");
                                }
                            }
                        }
                        System.out.println(sb.toString());
                        if (!sb.equals("")) {
                            timeStr = sb.toString() + "前";
                        } else {
                            timeStr = sb.toString();
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    map1.put("addTime", timeStr);

                    if (!isSelSub) {//查询子级评论的时候
                        //查询一条子级评论
                        List<Map> mapList2 = new ArrayList<>();
                        Wrapper<DiscussDO> wrapper2 = new EntityWrapper<DiscussDO>().orderBy("add_time", false);
                        wrapper2.eq("courses_id", Long.parseLong(id));
                        wrapper2.eq("root_id", discussDO.getId());

                        List<DiscussDO> discussDOS2 = discussService.selectList(wrapper2);
                        if (discussDOS2 != null && discussDOS2.size() > 0) {
                            Map map2 = new HashMap();
                            map2.put("id", discussDO.getId());

                            UserDO userDO2 = this.userService.selectById(discussDOS2.get(0).getUserId());
                            if (userDO2 != null) {
                                if (userDO2.getUsername() != null) {
                                    map2.put("userName", userDO2.getUsername());
                                } else {
                                    if (userDO2.getName() != null) {
                                        map2.put("userName", userDO2.getName());
                                    } else {
                                        map2.put("userName", "");
                                    }
                                }
                            } else {
                                map2.put("userName", "");
                            }
                            if (discussDOS2.get(0).getContent() != null) {
                                map2.put("content", discussDOS2.get(0).getContent());
                            } else {
                                map2.put("content", "");
                            }

                            if (discussDOS2.get(0).getIsDelete() != null) {
                                map2.put("isDelete", discussDOS2.get(0).getIsDelete());
                            } else {
                                map2.put("isDelete", 0);
                            }
                            mapList2.add(map2);
                        }
                        map1.put("children", mapList2);
                        map1.put("childrenSize", discussDOS2.size());
                    }
                    if (userDO.getId().equals(discussDO.getUserId())) {
                        map1.put("isCurrentUser", 1);
                    } else {
                        map1.put("isCurrentUser", 0);
                    }
                    mapList.add(map1);
                }
            }
            return ApiResult.success(mapList);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }


    //把 秒数 转换成天，时，分，秒。
    public com.alibaba.fastjson.JSONObject parseTimeSeconds(long t) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        String r = "";
        long day, hour, minute, second;
        day = t / 86400;
        hour = (t % 86400) / 3600;
        minute = (t % 86400 % 3600) / 60;
        second = t % 86400 % 3600 % 60;

        r = day + "," + hour + "," + minute + "," + second;
        System.out.println("秒数 " + t + " 转换成 天，时，分，秒,分别为：" + r);

        obj.put("day", day);
        obj.put("hour", hour);
        obj.put("minute", minute);
        obj.put("second", second);

        return obj;
    }

    //把 一个时间 加上天，时，分，秒
    public Calendar getTimeForAdd(int day, int hour, int minute, int second, Date date) {
        Calendar nowTime = Calendar.getInstance();
        if (date != null) {
            nowTime.setTime(date);
        } else {
            nowTime.clear();//1970年1月1日 0点0分0秒
        }
        nowTime.add(Calendar.DATE, day);
        nowTime.add(Calendar.HOUR, hour);
        nowTime.add(Calendar.MINUTE, minute);
        nowTime.add(Calendar.SECOND, second);
        return nowTime;
    }

    //把 一个时间 减去天，时，分，秒
    public Calendar getTimeForSub(int day, int hour, int minute, int second, Date date) {
        Calendar nowTime = Calendar.getInstance();
        if (date != null) {
            nowTime.setTime(date);
        } else {
            nowTime.clear();//1970年1月1日 0点0分0秒
        }
        nowTime.add(Calendar.DATE, -day);
        nowTime.add(Calendar.HOUR, -hour);
        nowTime.add(Calendar.MINUTE, -minute);
        nowTime.add(Calendar.SECOND, -second);
        return nowTime;
    }

    private static Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();

        todayStart.set(Calendar.HOUR, 0);

        todayStart.set(Calendar.MINUTE, 0);

        todayStart.set(Calendar.SECOND, 0);

        todayStart.set(Calendar.MILLISECOND, 0);

        return todayStart.getTime();

    }

    private static Date getEndTime() {
        Calendar todayEnd = Calendar.getInstance();

        todayEnd.set(Calendar.HOUR, 23);

        todayEnd.set(Calendar.MINUTE, 59);

        todayEnd.set(Calendar.SECOND, 59);

        todayEnd.set(Calendar.MILLISECOND, 999);

        return todayEnd.getTime();

    }


    /**
     * api小程序端-获取课程计划详情接口--公开方法，不需要登录
     *
     * @Description: 获取课程计划，参数：课程id，班级id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selMyCoursePlanDetials")
    @Log("api小程序端-获取课程计划详情接口")
    @ApiOperation(value = "api小程序端-获取课程计划详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selMyCoursePlanDetials(String id, String classId) {
        if (StringUtils.isNotBlank(id)) {
            Wrapper<CoursesClassDO> CoursesClassWrapper = new EntityWrapper<CoursesClassDO>().orderBy("id", false);
            CoursesClassWrapper.eq("courses_id", id);
            CoursesClassWrapper.eq("class_id", classId);
            List<CoursesClassDO> coursesClassDOS = coursesClassService.selectList(CoursesClassWrapper);
            if(coursesClassDOS.size()>0) {
                CoursesClassDO coursesClassDO = coursesClassDOS.get(0);
                String coursesName = "";
                if(coursesClassDO.getCourseIds()!=null){
                    System.out.println("coursesClassDO.getCourseIds():"+coursesClassDO.getCourseIds());
                    String[] idStr = coursesClassDO.getCourseIds().split(",");
                    if(idStr.length>0){
                        for(int a=0; a<idStr.length; a++){
                            CoursesDO coursesDO = this.coursesService.selectById(Long.valueOf(idStr[a]));
                            if (coursesDO != null) {
                                coursesName += coursesDO.getName();
                                if(a < idStr.length-1){
                                    coursesName += "、";
                                }
                            }
                        }
                    }
                }
                coursesClassDO.setCoursesName(coursesName);
                return ApiResult.success(coursesClassDO);
            }else {
                CoursesClassDO coursesClassDO = new CoursesClassDO();
                return ApiResult.success(coursesClassDO);
            }
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }


    /**
     * api小程序端-个人中心—我的课程计划列表接口
     *
     * @Description: 查询当前用户的课程计划列表信息；参数：页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @GetMapping("/selMyCoursePlanList")
    @Log("api小程序端-个人中心—我的课程计划列表接口")
    @ApiOperation("api小程序端-个人中心—我的课程计划列表接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyCoursePlanList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Wrapper<StuClassDO> StuClassWrapper = new EntityWrapper<StuClassDO>().orderBy("id", false);
        StuClassWrapper.eq("user_id", user.getId());
        StuClassWrapper.eq("status", 1);
        List<StuClassDO> stuClassDOS = stuClassService.selectList(StuClassWrapper);

        Wrapper<CoursesClassDO> CoursesClassWrapper = new EntityWrapper<CoursesClassDO>().orderBy("id", false);
        Page<CoursesClassDO> page = null;
        if (stuClassDOS.size() > 0) {
            CoursesClassWrapper.eq("class_id", stuClassDOS.get(0).getClassId());
            page = coursesClassService.selectPage(getPage(CoursesClassDO.class), CoursesClassWrapper);
            if (current != null && !current.equals("")) {
                page.setCurrent(Integer.valueOf(current));
            }
            if (number != null && !number.equals("")) {
                page.setSize(Integer.valueOf(number));

                if (page != null && page.getTotal() > 0) {
                    List list = new ArrayList();
                    for (int i = 0; i < page.getRecords().size(); i++) {
                        CoursesClassDO obj = page.getRecords().get(i);
                        CoursesDO coursesDO = this.coursesService.selectById(obj.getCoursesId());
                        if (coursesDO != null) {
                            //课程名
                            if (coursesDO.getName() != null) {
                                obj.setCourseName(coursesDO.getName());
                            } else {
                                obj.setCourseName("");
                            }
                            //缩略图
                            if (coursesDO.getThumbnail() != null) {
                                obj.setThumbnail(coursesDO.getThumbnail());
                            } else {
                                obj.setThumbnail("");
                            }

                            //讲师姓名
                            UserDO teacher = userService.selectById(coursesDO.getUserId());
                            if (teacher != null) {
                                obj.setTeacherName(teacher.getName());
                            } else {
                                obj.setTeacherName("");
                            }

                            //课程类型
                            if (coursesDO.getType() != null) {
                                obj.setType(coursesDO.getType());
                            }

                            //学习进度
                            obj.setProcess("0%");

                            list.add(obj);
                        }

                    }
                    page.setRecords(list);
                } else {
                    page.setRecords(null);
                }
            } else {
                page.setRecords(null);
            }
        }
        return ApiResult.success(page);
    }

    /**
     * api小程序端-个人中心—课后作业列表接口
     *
     * @Description: 查询当前课程 课后作业列表信息；参数：页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/selCourseAndTask")
    @Log("api小程序端-个人中心—课后作业列表接口")
    @ApiOperation(value = "api小程序端-个人中心—课后作业列表接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selCourseAndTask(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number, String classId, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if(classId==null || classId.equals("")){
            return ApiResult.fail("参数错误！");
        }
        System.out.println("current:"+current);
        System.out.println("number:"+number);
        /*if(courseId==null || courseId.equals("")){
            return ApiResult.fail("参数错误！");
        }*/

        Wrapper<PapersDeploymentDO> papersDeploymentDOWrapper = new EntityWrapper<PapersDeploymentDO>().orderBy("id", false);
        if(courseId!=null && !courseId.equals("")) {
            papersDeploymentDOWrapper.eq("courses_id", courseId);
        }
        papersDeploymentDOWrapper.eq("class_id", classId);
        Page<PapersDeploymentDO> page = papersDeploymentService.selectPage(getPage(PapersDeploymentDO.class), papersDeploymentDOWrapper);

        if (current != null && !current.equals("")) {
            page.setCurrent(Integer.valueOf(current));
        }
        if (number != null && !number.equals("")) {
            page.setSize(Integer.valueOf(number));

            if (page != null && page.getTotal() > 0) {
                List list = new ArrayList();
                for (int i = 0; i < page.getRecords().size(); i++) {
                    PapersDeploymentDO obj = page.getRecords().get(i);
                    CoursesDO coursesDO = this.coursesService.selectById(obj.getCoursesId());
                    if (coursesDO != null) {
                        //课程名
                        if (coursesDO.getName() != null) {
                            obj.setCourseName(coursesDO.getName());
                        } else {
                            obj.setCourseName("");
                        }
                        //是否已截止
                        Date sd1 = obj.getEndTime();
                        Date sd2 = new Date();

                        if(sd2.before(sd1)) {
                            obj.setIsOver(0);
                        }else {
                            obj.setIsOver(1);
                        }

                        SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
                        if(obj.getStartTime()!=null){
                            obj.setStartTimeStr(f.format(obj.getStartTime()));
                        }else {
                            obj.setStartTimeStr("");
                        }
                        if(obj.getEndTime()!=null){
                            obj.setEndTimeStr(f.format(obj.getEndTime()));
                        }else {
                            obj.setEndTimeStr("");
                        }

                        list.add(obj);
                    }

                }
                page.setRecords(list);
            } else {
                page.setRecords(null);
            }
        } else {
            page.setRecords(null);
        }
        return ApiResult.success(page);
    }


    /**
     * api小程序端-个人中心—课后作业详情接口
     *
     * @Description: 查询当前课程 课后作业详情信息；参数：页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/selTaskInfo")
    @Log("api小程序端-个人中心—课后作业详情接口")
    @ApiOperation(value = "api小程序端-个人中心—课后作业详情接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> taskInfo(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id){
        System.out.println("id:"+id);
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        int num = 0;
        double score = 0;
        List<Map> itmsType0Map = new ArrayList<>();
        List<Map> itmsType1Map = new ArrayList<>();
        List<Map> itmsType2Map = new ArrayList<>();
        List<Map> itmsType3Map = new ArrayList<>();
        List<Map> itmsType4Map = new ArrayList<>();

        PapersDeploymentDO papersDeploymentDO = papersDeploymentService.selectById(Long.parseLong(id));
        if(papersDeploymentDO!=null){
            map.put("id",id);

            //是否已截止
            Date sd1 = papersDeploymentDO.getEndTime();
            Date sd2 = new Date();

            if(sd2.before(sd1)) {
                map.put("isOver", 0);
            }else {
                map.put("isOver", 1);
            }

            boolean flag = false;
            Long submitId = 0L;
            //是否已经提交过
            Wrapper<StudentPaperSubmitDO> submitDOWrapper = new EntityWrapper<StudentPaperSubmitDO>().orderBy("id", false);
            submitDOWrapper.eq("stu_id", user.getId());
            submitDOWrapper.eq("papers_deployment_id", papersDeploymentDO.getId());
            List<StudentPaperSubmitDO> submitDOS = studentPaperSubmitService.selectList(submitDOWrapper);
            if(submitDOS.size()>0){
                flag = true;
                submitId = submitDOS.get(0).getId();
                map.put("submitId", submitId);
                map.put("submitStatus", submitDOS.get(0).getStatus());
            }else {
                map.put("submitId", "");
                map.put("submitStatus", "");
            }
            if(papersDeploymentDO.getItems()!=null){
               // System.out.println("papersDeploymentDO.getItems():"+papersDeploymentDO.getItems());
                String[] itemsStr = papersDeploymentDO.getItems().split(",");
                if(itemsStr.length>0){
                    for(int a = 0; a < itemsStr.length; a++){
                        if(!itemsStr[a].equals("")) {
                            MajorItemBankDO ItemBankDO = this.majorItemBankService.selectById(Long.valueOf(itemsStr[a]));
                            //System.out.println("1111:"+ItemBankDO.getId());
                            if(ItemBankDO!=null) {
                                if(ItemBankDO.getState()!=9) {//没有被删除
                                    num++;
                                    Map obj = new HashMap();
                                    obj.put("id", ItemBankDO.getId());
                                    obj.put("topic_content", ItemBankDO.getTopicContent());
                                    obj.put("type", ItemBankDO.getType());
                                    obj.put("options", ItemBankDO.getOptions());
                                    obj.put("score", ItemBankDO.getScore());
                                    score += ItemBankDO.getScore();
                                    obj.put("resource_type", ItemBankDO.getResourceType());
                                    obj.put("resource_url", ItemBankDO.getResourceUrl());
                                    String answer_student = "";
                                    if(flag) {
                                        Wrapper<StudentPaperSubmitAnswersDO> answersDOWrapper = new EntityWrapper<StudentPaperSubmitAnswersDO>().orderBy("id", false);
                                        answersDOWrapper.eq("items_id", ItemBankDO.getId());
                                        answersDOWrapper.eq("submit_id", submitId);
                                        List<StudentPaperSubmitAnswersDO> answersDOS = studentPaperSubmitAnswersService.selectList(answersDOWrapper);
                                        if (answersDOS.size() > 0) {
                                            answer_student = answersDOS.get(0).getAnswer();
                                            obj.put("answer", answersDOS.get(0).getAnswer());
                                            obj.put("getScore", answersDOS.get(0).getScore());
                                        } else {
                                            obj.put("answer", "");
                                            obj.put("getScore", "");
                                        }
                                    } else {
                                        obj.put("answer", "");
                                        obj.put("getScore", "");
                                    }

                                    List<Map> childrenList = new ArrayList<>();
                                    if(ItemBankDO.getType()!=4 && ItemBankDO.getType()!=3) {
                                        if (ItemBankDO.getOptions() != null) {
                                            String[] optionsList = ItemBankDO.getOptions().split(";;");
                                            if (optionsList.length > 0) {
                                                for (int b = 0; b < optionsList.length; b++) {
                                                    Map childrenMap = new HashMap();
                                                    childrenMap.put("value", optionsList[b]);
                                                    if (ItemBankDO.getType() == 0 || ItemBankDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                                                        if (optionsList[b].equals(answer_student)) {
                                                            childrenMap.put("selected", 1);
                                                        } else {
                                                            childrenMap.put("selected", 0);
                                                        }
                                                    } else if (ItemBankDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                                                        boolean isSelect = true;
                                                        if (answer_student == null || answer_student == "") {
                                                            isSelect = false;
                                                        } else {
                                                            String[] answer_studentList = answer_student.split(";;");
                                                            if (answer_studentList.length > 0) {
                                                                for (int n = 0; n < answer_studentList.length; n++) {
                                                                    if (optionsList[b].contains(answer_studentList[n])) {
                                                                        isSelect = false;
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        if (isSelect) {
                                                            childrenMap.put("selected", 1);
                                                        } else {
                                                            childrenMap.put("selected", 0);
                                                        }
                                                    }
                                                    childrenList.add(childrenMap);
                                                }
                                            }
                                        }

                                    }else if (ItemBankDO.getType() == 3) {//填空
                                       /* int bankNum = ItemBankDO.getTopicContent().indexOf("__");
                                        obj.put("bankNum", bankNum);*/
                                        String[] topicList = ItemBankDO.getTopicContent().split("__");
                                        String[] answerList = answer_student.split(";;");
                                        if(topicList.length>0) {
                                            for (int b = 0; b < topicList.length; b++) {
                                                Map childrenMap = new HashMap();
                                                childrenMap.put("topic", topicList[b]);
                                                if(answerList.length>0) {
                                                    if (answerList.length > b && answerList[b] != null && !answerList[b].equals("")) {
                                                        childrenMap.put("value", answerList[b]);
                                                    } else {
                                                        childrenMap.put("value", "");
                                                    }
                                                } else {
                                                    childrenMap.put("value", "");
                                                }
                                                childrenList.add(childrenMap);
                                            }
                                        }
                                    }else if (ItemBankDO.getType() == 4) {//问答
                                        Map childrenMap = new HashMap();
                                        childrenMap.put("value", answer_student);
                                        childrenList.add(childrenMap);
                                    }
                                    obj.put("childrenSize", childrenList.size());
                                    obj.put("children", childrenList);

                                    if(ItemBankDO.getType()==0) {
                                        itmsType0Map.add(obj);
                                    }
                                    if(ItemBankDO.getType()==1) {
                                        itmsType1Map.add(obj);
                                    }
                                    if(ItemBankDO.getType()==2) {
                                        itmsType2Map.add(obj);
                                    }
                                    if(ItemBankDO.getType()==3) {
                                        itmsType3Map.add(obj);
                                    }
                                    if(ItemBankDO.getType()==4) {
                                        itmsType4Map.add(obj);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            map.put("numStart" , 0);
            map.put("num" , num);
            map.put("score" , score);
            map.put("itmsType0" , itmsType0Map);
            map.put("itmsType1" , itmsType1Map);
            map.put("itmsType2" , itmsType2Map);
            map.put("itmsType3" , itmsType3Map);
            map.put("itmsType4" , itmsType4Map);
            map.put("itmsType0Num" , itmsType0Map.size());
            map.put("itmsType1Num" , itmsType1Map.size());
            map.put("itmsType2Num" , itmsType2Map.size());
            map.put("itmsType3Num" , itmsType3Map.size());
            map.put("itmsType4Num" , itmsType4Map.size());
            map.put("id" , id);

            return ApiResult.success(map);
        }else {
            return ApiResult.fail("参数错误！");
        }
    }


    /**
     * api小程序端-个人中心—提交作业接口
     *
     * @Description: 查询当前课程 提交作业信息；
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/submitTasksAnswer")
    @Log("api小程序端-个人中心—提交作业接口")
    @ApiOperation(value = "api小程序端-个人中心—提交作业接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> submitTasksAnswer(@RequestHeader(value = TOKEN_TAG, required = false) String token, String submitType
            , String papersDeploymentId, String submitId, String itmsAnswer
    ){

        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if(submitType == null || papersDeploymentId == null || submitId == null || itmsAnswer == null){
            return ApiResult.fail("参数错误！");
        }
        if(submitType .equals("") || papersDeploymentId .equals("") || itmsAnswer .equals("")){
            return ApiResult.fail("参数错误！");
        }

        PapersDeploymentDO papersDeploymentDO = papersDeploymentService.selectById(Long.parseLong(papersDeploymentId));
        if(papersDeploymentDO!=null){
            JSONArray answerArray = JSONArray.parseArray(itmsAnswer);//answer
            StudentPaperSubmitDO submitDO = null;

            if(submitId.equals("")){//新增
                submitDO = new StudentPaperSubmitDO();
                submitDO.setStatus(Integer.valueOf(submitType));
                submitDO.setPapersDeploymentId(Long.valueOf(papersDeploymentId));
                submitDO.setCreaterDate(new Date());
                submitDO.setStuId(user.getId());
                if(this.studentPaperSubmitService.insert(submitDO)){
                    if(answerArray!=null && answerArray.size()>0){
                        for(int a = 0; a<answerArray.size(); a++){
                            JSONObject obj = JSONArray.parseObject(answerArray.get(a)+"");
                            if(obj!=null && !obj.equals("")){
                                StudentPaperSubmitAnswersDO answersDO = new StudentPaperSubmitAnswersDO();
                                if(obj.get("id")!=null && !obj.get("id").toString().equals("")){
                                    answersDO.setItemsId(Long.valueOf(obj.get("id")+""));
                                    String answer = "";
                                    if(obj.get("answer")!=null) {
                                        answersDO.setAnswer(obj.get("answer")+"");
                                        answer = obj.get("answer")+"";
                                    }
                                    answersDO.setCreaterDate(new Date());
                                    double score = this.getScoreByItemsId(obj.get("id")+"", answer);
                                    answersDO.setScore(score);
                                    answersDO.setSubmitId(submitDO.getId());
                                    this.studentPaperSubmitAnswersService.insert(answersDO);
                                }
                            }
                        }
                    }
                }
            }else {//编辑
                submitDO = this.studentPaperSubmitService.selectById(submitId);
                submitDO.setStatus(Integer.valueOf(submitType));
                submitDO.setPapersDeploymentId(Long.valueOf(papersDeploymentId));
                submitDO.setUpdateDate(new Date());
                submitDO.setUpdaterId(user.getId());
                if(this.studentPaperSubmitService.updateById(submitDO)){
                    if(answerArray!=null && answerArray.size()>0){
                        for(int a = 0; a<answerArray.size(); a++){
                            JSONObject obj = JSONArray.parseObject(answerArray.get(a)+"");
                            if(obj!=null && !obj.equals("")){
                                StudentPaperSubmitAnswersDO answersDO = null;
                                if(obj.get("id")!=null && !obj.get("id").toString().equals("")){
                                    //是否已有记录
                                    Wrapper<StudentPaperSubmitAnswersDO> answersDOWrapper = new EntityWrapper<StudentPaperSubmitAnswersDO>().orderBy("id", false);
                                    answersDOWrapper.eq("submit_id", submitDO.getId());
                                    answersDOWrapper.eq("items_id", Long.valueOf(obj.get("id")+""));
                                    List<StudentPaperSubmitAnswersDO> answersDOS = studentPaperSubmitAnswersService.selectList(answersDOWrapper);
                                    if(answersDOS.size()>0){
                                        answersDO = this.studentPaperSubmitAnswersService.selectById(answersDOS.get(0).getId());
                                        answersDO.setItemsId(Long.valueOf(obj.get("id")+""));
                                        String answer = "";
                                        if(obj.get("answer")!=null) {
                                            answersDO.setAnswer(obj.get("answer")+"");
                                            answer = obj.get("answer")+"";
                                        }
                                        answersDO.setCreaterDate(new Date());
                                        double score = this.getScoreByItemsId(obj.get("id")+"", answer);
                                        answersDO.setScore(score);
                                        this.studentPaperSubmitAnswersService.updateById(answersDO);
                                    }else {
                                        answersDO = new StudentPaperSubmitAnswersDO();
                                        answersDO.setItemsId(Long.valueOf(obj.get("id")+""));
                                        String answer = "";
                                        if(obj.get("answer")!=null) {
                                            answersDO.setAnswer(obj.get("answer")+"");
                                            answer = obj.get("answer")+"";
                                        }
                                        answersDO.setCreaterDate(new Date());
                                        double score = this.getScoreByItemsId(obj.get("id")+"", answer);
                                        answersDO.setScore(score);
                                        this.studentPaperSubmitAnswersService.insert(answersDO);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            ApiResult apiResult= new ApiResult<>();
            apiResult.setCode(ApiEnumError.success.getCode());
            apiResult.setData(1);
            return apiResult;
        }else {
            return ApiResult.fail("参数错误！");
        }
    }

    public double getScoreByItemsId(String id, String answer){
        double score = 0;
        if(id != null && !id.equals("")){
            MajorItemBankDO ItemBankDO = this.majorItemBankService.selectById(Long.valueOf(id));
            if(ItemBankDO!=null) {
                if (ItemBankDO.getType() != 4 && ItemBankDO.getType() != 3) {
                    if (ItemBankDO.getRightKey() != null) {
                        String[] rightKeyList = ItemBankDO.getRightKey().split(";;");
                        if (rightKeyList.length > 0) {
                            int trueNum = 0;
                            for (int b = 0; b < rightKeyList.length; b++) {
                                if (ItemBankDO.getType() == 0 || ItemBankDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                                    if (rightKeyList[b].equals(answer)) {
                                        score = ItemBankDO.getScore();
                                    }
                                } else if (ItemBankDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                                    if (answer != null && !answer.equals("")) {
                                        String[] answer_studentList = answer.split(";;");

                                        if (answer_studentList.length > 0) {
                                            for (int n = 0; n < answer_studentList.length; n++) {
                                                if (rightKeyList[b].contains(answer_studentList[n])) {
                                                    trueNum++;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (ItemBankDO.getType() == 1) {
                                if (trueNum == rightKeyList.length) {
                                    score = ItemBankDO.getScore();
                                }
                            }
                        }
                    }

                } else if (ItemBankDO.getType() == 3) {//填空
                    int correctNum = 0;
                    int bankNum = ItemBankDO.getTopicContent().indexOf("__");
                    String[] answerList = answer.split(";;");
                    String[] rightKeyList = ItemBankDO.getRightKey().split(";;");
                    if (bankNum > 0) {
                        for (int b = 0; b < bankNum; b++) {
                            if (answerList.length > 0) {
                                if (answerList.length > b && answerList[b] != null && !answerList[b].equals("")) {
                                    if(answerList[b].equals(rightKeyList[b])){
                                        correctNum++;
                                    }
                                }
                            }
                        }
                    }

                    double scoreAvg = 0;
                    if(ItemBankDO.getScore()!=0 && bankNum!=0){
                        scoreAvg = ItemBankDO.getScore()/bankNum;
                    }
                    score = scoreAvg * correctNum;
                }
            }
        }
        return score;
    }


    /**
     * api小程序端-个人中心—班级考试列表接口
     *
     * @Description: 查询当前课程 课后作业列表信息；参数：页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/selCourseAndExamnation")
    @Log("api小程序端-个人中心—班级考试列表接口")
    @ApiOperation(value = "api小程序端-个人中心—班级考试列表接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selCourseAndExamnation(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number, String classId, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if(classId==null || classId.equals("")){
            return ApiResult.fail("参数错误！");
        }

       /* if(courseId==null || courseId.equals("")){
            return ApiResult.fail("参数错误！");
        }*/


        Wrapper<ClassesExaminationPaperDO> CEPWrapper = new EntityWrapper<ClassesExaminationPaperDO>().orderBy("id", false);
        if(courseId!=null && !courseId.equals("")) {
            CEPWrapper.eq("courses_id", courseId);
        }
        CEPWrapper.eq("class_id", classId);
        Page<ClassesExaminationPaperDO> page = classesExaminationPaperService.selectPage(getPage(ClassesExaminationPaperDO.class), CEPWrapper);

        if (current != null && !current.equals("")) {
            page.setCurrent(Integer.valueOf(current));
        }
        if (number != null && !number.equals("")) {
            page.setSize(Integer.valueOf(number));

            if (page != null && page.getTotal() > 0) {
                List list = new ArrayList();
                for (int i = 0; i < page.getRecords().size(); i++) {
                    ClassesExaminationPaperDO obj = page.getRecords().get(i);
                    Wrapper<ClassesExaminationSubmitDO> CESWrapper = new EntityWrapper<ClassesExaminationSubmitDO>().orderBy("id", false);
                    CESWrapper.eq("stu_id", user.getId());
                    CESWrapper.eq("classes_examination_paper_id", obj.getId());
                    List<ClassesExaminationSubmitDO> CESDOS = classesExaminationSubmitService.selectList(CESWrapper);
                    if(CESDOS.size()>0){
                        obj.setIsSubmit(1);
                        obj.setAnswerId(CESDOS.get(0).getId());
                    }else {
                        obj.setIsSubmit(0);
                    }
                    CoursesDO coursesDO = this.coursesService.selectById(obj.getCoursesId());
                    if (coursesDO != null) {
                        //课程名
                        if (coursesDO.getName() != null) {
                            obj.setCourseName(coursesDO.getName());
                        } else {
                            obj.setCourseName("");
                        }
                        //是否已截止
                        Date endTime = obj.getEndTime();
                        Date startTime = obj.getStartTime();
                        Date newDate = new Date();


                        if(newDate.before(endTime)) {
                            obj.setIsOver(0);
                        }else {
                            obj.setIsOver(1);
                        }

                        if(newDate.before(startTime)) {
                            obj.setShowType("0");
                        }else if(endTime.before(newDate)) {
                            if(CESDOS.size()>0){
                                obj.setShowType("1");
                            }else {
                                obj.setShowType("");
                            }
                        }else {
                            if(CESDOS.size()>0){
                                obj.setShowType("1");
                            }else {
                                obj.setShowType("0");
                            }
                        }

                        SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
                        if(obj.getStartTime()!=null){
                            obj.setStartTimeStr(f.format(obj.getStartTime()));
                        }else {
                            obj.setStartTimeStr("");
                        }
                        if(obj.getEndTime()!=null){
                            obj.setEndTimeStr(f.format(obj.getEndTime()));
                        }else {
                            obj.setEndTimeStr("");
                        }

                        list.add(obj);
                    }

                }
                page.setRecords(list);
            } else {
                page.setRecords(null);
            }
        } else {
            page.setRecords(null);
        }
        return ApiResult.success(page);
    }

    /**
     * api小程序端-个人中心—获取班级考试试卷
     *
     * @Description: 获取班级考试试卷
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/selClassesExamnation")
    @Log("api小程序端-个人中心—获取班级考试试卷")
    @ApiOperation(value = "api小程序端-个人中心—获取班级考试试卷", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selClassesExamnation(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id, String type) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if(id==null || id.equals("")){
            return ApiResult.fail("参数错误！");
        }
        if(type==null){
            return ApiResult.fail("参数错误！");
        }


        Map mapre = new HashMap();
        ClassesExaminationSubmitDO CES = new ClassesExaminationSubmitDO();
        ClassesExaminationPaperDO CEP = this.classesExaminationPaperService.selectById(Long.valueOf(id));
        if(CEP!=null){
            Wrapper<ClassesExaminationSubmitDO> CESWrapper = new EntityWrapper<ClassesExaminationSubmitDO>().orderBy("id", false);
            CESWrapper.eq("stu_id", user.getId());
            CESWrapper.eq("classes_examination_paper_id", CEP.getId());
            List<ClassesExaminationSubmitDO> CESDOS = classesExaminationSubmitService.selectList(CESWrapper);
            if(type.equals("")) {
                if(CESDOS.size()>0){
                    return ApiResult.fail("已经参加过该考试！");
                }
            }


            double scoreSum = 0;
            boolean flag = false;
            Long submitId = 0L;

            if(CESDOS.size()>0){
                CES = CESDOS.get(0);
                flag = true;
                submitId = CESDOS.get(0).getId();
            }

            CES.setUserName(user.getName());
            System.out.println("CEP.getName():"+CEP.getName());
            CES.setPapersName(CEP.getName());

            mapre.put("id", CEP.getId());//试卷id
            mapre.put("name", CEP.getName());//试卷名称
            mapre.put("numbers", CEP.getNumbers());//试卷编号

            List<Map> array = new ArrayList();

            if(CEP.getItems()!=null){
                String[] itemsList = CEP.getItems().split(",");
                if( itemsList.length>0 ){
                    for(int a=0; a<itemsList.length; a++){
                        if(!itemsList[a].equals("")) {
                            Map imap = new HashMap();
                            MajorItemBankDO MI = this.majorItemBankService.selectById(Long.valueOf(itemsList[a]));
                            if( MI != null ){
                                imap.put("id", MI.getId());
                                imap.put("introduce", MI.getTopicContent());
                                imap.put("options", MI.getOptions());
                                imap.put("score", MI.getScore());
                                imap.put("titleNumber", (a+1));
                                imap.put("type", MI.getType());
                                if(MI.getType() == 3){
                                    List<Map> childrenList = new ArrayList<>();
                                    String[] topicList = MI.getTopicContent().split("__");
                                    if(topicList.length>0) {
                                        for (int b = 0; b < topicList.length; b++) {
                                            Map childrenMap = new HashMap();
                                            childrenMap.put("topic", topicList[b]);
                                            childrenList.add(childrenMap);
                                        }
                                    }
                                    imap.put("children", childrenList);
                                }

                                if(type.equals("answer")) {//是否获取考生答案
                                    String answer_student = "";
                                    double getScore = 0;
                                    List<ClassesExaminationSubmitAnswersDO> answersDOS = new ArrayList<>();
                                    if(flag) {
                                        Wrapper<ClassesExaminationSubmitAnswersDO> answersDOWrapper = new EntityWrapper<ClassesExaminationSubmitAnswersDO>().orderBy("id", false);
                                        answersDOWrapper.eq("submit_id", submitId);
                                        answersDOWrapper.eq("items_id", MI.getId());
                                        answersDOS = classesExaminationSubmitAnswersService.selectList(answersDOWrapper);
                                        if (answersDOS.size() > 0) {
                                            answer_student = answersDOS.get(0).getAnswer();
                                            getScore = answersDOS.get(0).getScore();
                                            scoreSum += getScore;
                                        }
                                    }
                                    imap.put("answer", answer_student);
                                    if(MI.getRightKey()!=null) {
                                        imap.put("rightKey", MI.getRightKey());
                                    }else {
                                        imap.put("rightKey", "");
                                    }
                                    imap.put("topicAnalysis", MI.getTopicAnalysis());//题目解析
                                    if(getScore == MI.getScore()) {
                                        imap.put("yesOrNo", "是");
                                    }else {
                                        imap.put("yesOrNo", "否");
                                    }
                                }
                                array.add(imap);
                            }
                        }
                    }
                }
            }
            if(type.equals("answer")) {
                CES.setAnswerLists(array);
                CES.setScore(scoreSum);
                return ApiResult.success(CES);
            }else {
                mapre.put("questions", array);
                return ApiResult.success(mapre);
            }

        }else {
            return ApiResult.fail("暂无试卷，敬请期待！");
        }
    }


    /**
     * api小程序端-个人中心—班级试卷提交接口
     *
     * @Description: 班级试卷提交
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/submitClassesExamnation")
    @Log("api小程序端-个人中心—班级试卷提交")
    @ApiOperation(value = "api小程序端-个人中心—班级试卷提交", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> submitClassesExamnation(@RequestHeader(value = TOKEN_TAG, required = false) String token,  String id, String answerList, String time, String type) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if(id==null || id.equals("")){
            return ApiResult.fail("参数错误！");
        }
        if(type==null){
            return ApiResult.fail("参数错误！");
        }
        if(answerList==null || answerList.equals("")){
            return ApiResult.fail("参数错误！");
        }
        if(time==null || time.equals("")){
            return ApiResult.fail("参数错误！");
        }

        ClassesExaminationPaperDO CEP = this.classesExaminationPaperService.selectById(Long.valueOf(id));
        if(CEP!=null){
            JSONArray answerArray = JSONArray.parseArray(answerList);//answer

            ClassesExaminationSubmitDO submitDO = null;

            Wrapper<ClassesExaminationSubmitDO> CESWrapper = new EntityWrapper<ClassesExaminationSubmitDO>().orderBy("id", false);
            CESWrapper.eq("stu_id", user.getId());
            CESWrapper.eq("classes_examination_paper_id", CEP.getId());
            List<ClassesExaminationSubmitDO> CESDOS = classesExaminationSubmitService.selectList(CESWrapper);
            boolean flag = false;
            if(CESDOS.size()>0){
                submitDO = CESDOS.get(0);
                submitDO.setStatus(0);
                submitDO.setClassesExaminationPaperId(CEP.getId());
                submitDO.setUpdateDate(new Date());
                submitDO.setStuId(user.getId());
                if(this.classesExaminationSubmitService.updateById(submitDO)) {
                    flag = true;
                }
            }else {
                submitDO = new ClassesExaminationSubmitDO();
                submitDO.setStatus(0);
                submitDO.setClassesExaminationPaperId(CEP.getId());
                submitDO.setCreaterDate(new Date());
                submitDO.setStuId(user.getId());
                if(this.classesExaminationSubmitService.insert(submitDO)) {
                    flag = true;
                }
            }
            double scoreSum = 0;
            if(flag) {
                if (answerArray != null && answerArray.size() > 0) {

                    for (int a = 0; a < answerArray.size(); a++) {
                        JSONObject obj = JSONArray.parseObject(answerArray.get(a) + "");
                        if (obj != null && !obj.equals("")) {
                            //是否已有记录
                            Wrapper<ClassesExaminationSubmitAnswersDO> answersDOWrapper = new EntityWrapper<ClassesExaminationSubmitAnswersDO>().orderBy("id", false);
                            answersDOWrapper.eq("submit_id", submitDO.getId());
                            answersDOWrapper.eq("items_id", Long.valueOf(obj.get("id")+""));
                            List<ClassesExaminationSubmitAnswersDO> answersDOS = classesExaminationSubmitAnswersService.selectList(answersDOWrapper);
                            if(answersDOS.size()>0) {
                                ClassesExaminationSubmitAnswersDO answersDO = answersDOS.get(0);
                                if (obj.get("id") != null && !obj.get("id").toString().equals("")) {
                                    answersDO.setItemsId(Long.valueOf(obj.get("id") + ""));
                                    String answer = "";
                                    if (obj.get("value") != null) {
                                        answersDO.setAnswer(obj.get("value") + "");
                                        answer = obj.get("value") + "";
                                    }
                                    answersDO.setCreaterDate(new Date());
                                    double score = this.getScoreByItemsId(obj.get("id") + "", answer);
                                    scoreSum += score;
                                    answersDO.setScore(score);
                                    answersDO.setSubmitId(submitDO.getId());
                                    this.classesExaminationSubmitAnswersService.updateById(answersDO);
                                }
                            }else {
                                ClassesExaminationSubmitAnswersDO answersDO = new ClassesExaminationSubmitAnswersDO();
                                if (obj.get("id") != null && !obj.get("id").toString().equals("")) {
                                    answersDO.setItemsId(Long.valueOf(obj.get("id") + ""));
                                    String answer = "";
                                    if (obj.get("value") != null) {
                                        answersDO.setAnswer(obj.get("value") + "");
                                        answer = obj.get("value") + "";
                                    }
                                    answersDO.setCreaterDate(new Date());
                                    double score = this.getScoreByItemsId(obj.get("id") + "", answer);
                                    scoreSum += score;
                                    answersDO.setScore(score);
                                    answersDO.setSubmitId(submitDO.getId());
                                    this.classesExaminationSubmitAnswersService.insert(answersDO);
                                }
                            }
                        }
                    }
                    submitDO.setTotalScore(scoreSum);
                    submitDO.setTimes(Long.parseLong(time));

                    if (scoreSum >= CEP.getPassMark()) {
                        submitDO.setStatus(1);//状态修改为通过
                    }
                    boolean saveflag = classesExaminationSubmitService.updateById(submitDO);
                    if (!saveflag) {
                        return ApiResult.fail("答卷已保存，但成绩保存错误，请稍后重试或联系管理员！");
                    }
                }
                Map map = new HashMap();
               // map.put("score", scoreSum);
                map.put("paperId", CEP.getId());//答卷id
                return ApiResult.success(map);
            }else {
                return ApiResult.fail("答卷错误，请稍后重试或联系管理员！");
            }
        }else {
            return ApiResult.fail("暂无试卷，敬请期待！");
        }
    }



    /**
     * api小程序端-个人中心—获取班级考试时间接口
     *
     * @Description: 获取班级考试时间
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/getExamTime")
    @Log("api小程序端-个人中心—获取班级考试时间")
    @ApiOperation(value = "api小程序端-个人中心—获取班级考试时间", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> getExamTime(@RequestHeader(value = TOKEN_TAG, required = false) String token,  String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if(id==null || id.equals("")){
            return ApiResult.fail("参数错误！");
        }

        ClassesExaminationPaperDO CEP = this.classesExaminationPaperService.selectById(Long.valueOf(id));
        if(CEP!=null){
            //是否已截止
            Date endTime = CEP.getEndTime();
            Date startTime = CEP.getStartTime();
            Date newDate = new Date();

            if(newDate.before(startTime)) {
                return ApiResult.fail("考试时间还未到！");
            }else if(endTime.before(newDate)) {
                return ApiResult.fail("已超过考试截止时间！");
            }else {
                return ApiResult.success("在考试时间期间！");
            }
        }else {
            return ApiResult.fail("暂无试卷，敬请期待！");
        }
    }

    /**
     * api小程序端-个人中心—获取当前用户是否已经提交过班级考试接口
     *
     * @Description: 获取当前用户是否已经提交过班级考试
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @PostMapping("/getIsSubmit")
    @Log("api小程序端-个人中心—获取当前用户是否已经提交过班级考试")
    @ApiOperation(value = "api小程序端-个人中心—获取当前用户是否已经提交过班级考试", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> getIsSubmit(@RequestHeader(value = TOKEN_TAG, required = false) String token ,String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if(id==null || id.equals("")){
            return ApiResult.fail("暂无试卷，敬请期待");
        }
        Map map = new HashMap();

        ClassesExaminationPaperDO CEP = this.classesExaminationPaperService.selectById(Long.valueOf(id));
        if(CEP!=null) {
            Wrapper<ClassesExaminationSubmitDO> CESWrapper = new EntityWrapper<ClassesExaminationSubmitDO>().orderBy("id", false);
            CESWrapper.eq("stu_id", user.getId());
            CESWrapper.eq("classes_examination_paper_id", CEP.getId());
            List<ClassesExaminationSubmitDO> CESDOS = classesExaminationSubmitService.selectList(CESWrapper);
            if (CESDOS.size() > 0) {
                map.put("isSubmit", 1);
            }else {
                map.put("isSubmit", 0);
            }
        }else {
            map.put("isSubmit", 0);
        }
        return ApiResult.success(map);
    }

}
